let port;

chrome.runtime.onInstalled.addListener(function () {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
        chrome.declarativeContent.onPageChanged.addRules([
            {
                conditions: [
                    // 只有打开百度才显示pageAction
                    new chrome.declarativeContent.PageStateMatcher({pageUrl: {urlContains: 'localhost'}})
                ],
                actions: [new chrome.declarativeContent.ShowPageAction()]
            }
        ]);
    });
});


chrome.runtime.onConnect.addListener(port => {
    // @TODO: release connection when disconnected

    this.port = port;
    this.port.onMessage.addListener((message, sender, reply) => {
        const tabId = message.tabId !== undefined ? message.tabId : sender.sender.tab.id;

        if (this.port.name === 'contentScript') {
            console.log("tabId: " + tabId)
            console.log("action: " + message.actions)
        }
    });

});

// send message to contentScript via background
//最重要的，将操作数据通过消息传递到XRDevice，从而调整姿势状态等
const postMessage = (message) => {
    if (this.port != null) {
        this.port.postMessage(message);
    }
};

const notifyPoseChange = (node) => {
    postMessage({
        action: 'webxr-pose',
        position: node.position.toArray([]), // @TODO: reuse array
        quaternion: node.quaternion.toArray([]) // @TODO: reuse array
    });
};

const notifyDeviceChange = (deviceDefinition) => {
    postMessage({
        action: 'webxr-device',
        deviceDefinition: deviceDefinition
    });
};

const notifyStereoEffectChange = (enabled) => {
    postMessage({
        action: 'webxr-stereo-effect',
        enabled: enabled
    });
};

const notifyExitImmersive = () => {
    postMessage({
        action: 'webxr-exit-immersive'
    });
};


const HEADSET = '0';

const assetNodes = {};
assetNodes[HEADSET] = null;

// @TODO: Currently the values are　groundless.
//        Set more appropriate values.
const defaultTransforms = {};
defaultTransforms[HEADSET] = {
    position: new THREE.Vector3(0, 1.6, 0),
    rotation: new THREE.Euler(0, 0, 0)
};

ConfigurationManager.createFromJsonFile('src/devices.json').then(manager => {
    createFakeHead();
    notifyDeviceChange(manager.devices["Google cardboard"]);
    notifyStereoEffectChange(true)
});

const createFakeHead = () => {
    const parent = new THREE.Object3D();
    parent.position.copy(defaultTransforms[HEADSET].position);
    parent.rotation.copy(defaultTransforms[HEADSET].rotation);
    assetNodes[HEADSET] = parent;

}

const test = () => {
    assetNodes[HEADSET].rotation.x = 1
    assetNodes[HEADSET].rotation.y = 1
    assetNodes[HEADSET].rotation.z = 1
    notifyPoseChange(assetNodes[HEADSET])
}

const resetPose = () => {
    assetNodes[HEADSET].position.copy(defaultTransforms[HEADSET].position);
    assetNodes[HEADSET].rotation.copy(defaultTransforms[HEADSET].rotation);
    notifyPoseChange(assetNodes[HEADSET])
}
